//
//  ZCNetworkTools.swift
//  weibo
//
//  Created by 张城 on 16/7/22.
//  Copyright © 2016年 张城. All rights reserved.
//

import UIKit
import AFNetworking


enum ZCNetworkToolsType: String {
    case GET = "GET"
    case POST = "POST"
}

class ZCNetworkTools: AFHTTPSessionManager {
    static let sharedTool: ZCNetworkTools = {
        let tool = ZCNetworkTools()
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tool
    }()
    
    func request(type: ZCNetworkToolsType, urlStr: String, parameter: AnyObject?,success:(response: AnyObject?)->(),failure: (error: NSError)->()) {
        
        if type == .POST {
            POST(urlStr, parameters: parameter, progress: nil, success: { (_, res) in
                success(response: res)
                }, failure: { (_, err) in
                    failure(error: err)
            })
        }else{
            GET(urlStr, parameters: parameter, progress: nil, success: { (_, res) in
                success(response: res)
                }, failure: { (_, err) in
                    failure(error: err)
            })
        }
    }
}

extension ZCNetworkTools {
    func oauthLoadUserAccount(code: String, success:(response: AnyObject?)->(),failure: (error: NSError)->())  {
        let urlS = "https://api.weibo.com/oauth2/access_token"
        
        let param = [
            "client_id" : APPKEY,
            "client_secret" : APPSecret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : APPREDIRECT_URI
        ]
        request(.POST, urlStr: urlS, parameter: param, success: success, failure: failure)
    }
    
    
    func oauthLoadUserInfo(userAccount: ZCUserAccount,success:(response: AnyObject?)->(),failure: (error: NSError)->()) {
        
        let urlStr = "https://api.weibo.com/2/users/show.json"
        let param = [
            "access_token" : userAccount.access_token!,
            "uid" : userAccount.uid!
        ]
        request(.GET, urlStr: urlStr, parameter: param, success: success, failure: failure)
    }
    
    
    
    
    
    
    func homeLoadUserDetailInfo(sinceId: Int64, maxId: Int64 ,success:(response: AnyObject?)->() ,failure: (error: NSError)->() ) {
        let urlStr = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let param = ["access_token" : ZCuserAccountViewModel.sharedTools.accessToken!,
                     "since_id" : "\(sinceId)",
                     "max_id" : "\(maxId)"
        ]
        
        request(.GET, urlStr: urlStr, parameter: param, success: success, failure: failure)
        
    }
    
}


























